<template>
  <div class="hello test-1" ref="resizeElementRef" @scroll="handleScroll">
    <div
        v-for="item in dataArray"
        :key="item.id"
        :style="itemStyle"
        :class="{'item': true, 'selected': item.id === selectedId }"
        @click="selectPerson(item)"
    >
      {{ variesWithWidth(item) }}
    </div>


    <div v-if="isBottom" class="bottom">
      {{ bottomText }}
    </div>

  </div>
</template>

<script>
export default {
  name: 'ScrollData',
  props: {
    showParams: String,
    bottomText: String,
    totalPages: Number,
    viewportHeight: Number,
    showing: Array,
    itemStyle: {
      type: Object,
      default: () => {

      }
    },
    dataArray: {
      type: Array,
      default: () => {
        return []
      }
    },

  },

  data() {
    return {
      timerId: null, // 定时器标识
      pageNum: 1, // 每次触发触底时的页数记录
      isBottom: false, // 是否最后一页
      elementWidth: 0,
      selectedId: null
    }
  },

  watch: {
    viewportHeight(valNew) {
      document.querySelector('.hello').style.height = valNew + 'px'
    },
    dataArray() {
      this.$nextTick(() => {
        this.setItemStyle();
      })
    }
  },

  async mounted() {
    await this.setTImeOutMyScroll()
    this.createResizeObserver();
  },

  methods: {
    async handleScroll({target}) {

      if (Math.abs(target.scrollHeight - target.scrollTop - target.clientHeight) <= 1) {
        if (this.pageNum !== this.totalPages) {
          this.pageNum++
          await this.setTImeOutMyScroll()
        } else {
          this.isBottom = true
        }
      }
    },

    async setTImeOutMyScroll() { // 简单的节流
      this.$parent.isOpenTimers = true
      // 如果已有定时器，先清除
      if (this.timerId) {
        clearTimeout(this.timerId);
      }

      // 设置新的定时器
      this.timerId = setTimeout(() => {
        this.$emit('nextPage', this.pageNum)
      }, 500);
    },

    /**
     * 定制item的样式
     */
    setItemStyle() {
      const items = document.querySelectorAll('.item')
      items.forEach((item) => {
        for (let itemStyleKey in this.itemStyle) {
          if (itemStyleKey === 'height') {
            item.style['lineHeight'] = this.itemStyle['height']
          } else {
            item.style[itemStyleKey] = this.itemStyle[itemStyleKey]
          }
        }
      })
    },

    // 检查宽度展示不同内容
    variesWithWidth(item){
      if (this.elementWidth < 240){
        return item[this.showParams] || item.name
      }else if (this.elementWidth < 340){
        return `${item[this.showParams]}(${item[this.showing[0][0]]})` || `${item.name}(${item[this.showing[0][0]]})`
      }else if (this.elementWidth > 340){
        return `${item[this.showParams]}(${item[this.showing[1][0]]}，${item[this.showing[1][1]]})` || `${item.name}(${item[this.showing[1][0]]}，${item[this.showing[1][1]]}))`
      }
    },

    createResizeObserver() {
      this.resizeObserver = new ResizeObserver(entries => {
        for (let entry of entries) {
          if (entry.target === this.$refs.resizeElementRef) {
            this.elementWidth = entry.contentRect.width;
          }
        }
      });
      this.resizeObserver.observe(this.$refs.resizeElementRef);
    },
    destroyResizeObserver() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
    },
    selectPerson(item){
      this.selectedId = item.id
      this.$emit('clickNode', item)
    }
  },
  beforeDestroy() {
    this.destroyResizeObserver();
  }
}
</script>

<style scoped>
.item {
  cursor: pointer;
}

.item:hover {
  background: #e0fff6 !important;
}

.selected{
  background: #e0fff6 !important;
}

.bottom {
  width: 100%;
  height: 30px;
  font-size: 20px;
  text-align: center;
  line-height: 30px;
}

/*滚动条的盒子*/
.test-1::-webkit-scrollbar {
  width: 8px;
  height: 1px;
  border: none;
}

/*滚动条里面小方块*/
.test-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #dbeeff;
  border: none;
}

/*滚动条里面轨道*/
.test-1::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ffffff;
  border: none;
}
</style>
